/**
 * @description useRelation 表的内容
 * @author 印明帝
 */
const { Blog,User,AtRelation } = require('../db/model/index')
const { formatBlogs } = require('./_format')


/**
  * 创建@ 关系
  * @method createAtRelation
  * @param {Number} userId 
  * @param {Number} blogId 
  * @returns {Promise}
  */
async function createAtRelation(userId,blogId){
  let result = AtRelation.create({
    userId,
    blogId
  })
  return result
}

/**
 * 获取at的数量
 * @method getAtRelationCount
 * @param {Number} userId 
 * @returns {promise}
 */
async function getAtRelationCount(userId) {
  let result = await AtRelation.findAndCountAll({
    where: {
      userId,
      isRead: false
    }
  })
  return result.count
}

/**
 * 获取atme的微博
 * @method getAtUserBlogList
 * @param {Number} userId 
 * @returns {promise}
 */
async function getAtUserBlogList(userId,index=0) {
  let limit = 10
  let offset = index*limit
  let result = await Blog.findAndCountAll({
    limit,
    offset,
    order: [
      ['id', 'desc']
    ],
    include: [
      // @ 关系
      {
        model: AtRelation,
        attributes: ['userId', 'blogId'],
        where: { userId }
      },
      // User
      {
        model: User,
        attributes: ['id', 'nickName', 'picture']
      }
    ]
  })
  
  
  return formatBlogs(result)
}

/**
 * 修改isRead
 * @method updateAtRelation
 * @param {*} userId 
 * @returns {promise}
 */
async function updateAtRelation(userId) {
  let result = await AtRelation.update({
    isRead: true
  },{
    where: {
      userId,
      isRead: false
    }
  })
  return result[0] > 0
}
module.exports = {
  createAtRelation,
  getAtRelationCount,
  getAtUserBlogList,
  updateAtRelation
}